<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager;
use app\common\constant\Constant;
use app\common\library\Aes;
use app\common\library\Wechat;
use app\common\model\Agreement;
use app\common\model\Authentication;
use app\common\model\Config;
use app\common\model\Match;
use app\common\model\MatchApply;
use app\common\model\Member;
use app\common\model\Order;
use app\common\model\Region;
use app\common\model\RelationImage;
use app\common\model\Round;
use app\common\model\Roundmember;
use app\common\model\Signrecord;
use app\common\model\Team;
use app\common\model\User;
use app\common\model\UserAccount;
use think\Db;
use think\Exception;

class MatchManager extends BaseManager
{

    /**
     * 门店赛事申请
     * @param User $user
     * @param int $storeId
     * @param array $data
     * @param bool $trans
     * @return array
     */
     public static function MatchApply(User $user,int $storeId,array $data,bool $trans=true):array
     {
         if ($trans)
             Db::startTrans();
         try {

             $result = EmployeeManager::authCheck($user->id,$storeId,Team::IS_STORE_YES,null,EmployeeManager::TYPE_DEFAULT);
             if ($result['code'] != EmployeeManager::$successCode){
                 throw new Exception($result['message']);
             }

             $value = Config::where('name','reapply_match_enable')->value('value');
             if ($value && MatchApply::where('store_id',$storeId)->where('status',MatchApply::STATUS_REJECT)->count()){
                 throw new Exception('您当前无法重申赛事');
             }

             if (MatchApply::where('merchant_id',$user->merchant_id)->where('store_id',$storeId)->where('status',MatchApply::STATUS_INIT)->count()){
                 throw new Exception('当前已申请，请耐心等待');
             }
             $data['store_id'] = $storeId;
             $data['merchant_id'] = $user->merchant_id;
             $data['user_id'] = $user->id;
             $matchApply = new MatchApply();
             $id = $matchApply->insertGetId($data);
             if (!$id){
                 throw new Exception('申请失败');
             }
             if ($trans)
                 Db::commit();
             self::setStatusCode(self::$successCode);
             self::setMessage(self::$successMessage);
             self::setData(['id'=>$id]);
         }catch (Exception $e){
             if ($trans)
                 Db::rollback();
             self::setStatusCode(self::$failCode);
             self::setMessage($e->getMessage());
         }
         return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
     }

    /**
     * 获取门店申请记录列表
     * @param User $user
     * @param $storeId
     * @param $status
     * @param $page
     * @param $step
     * @return array
     */
     public static function applyList(User $user,$storeId,$status=null,$page=1,$step=10)
     {
         $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
         try {
             if ($page < 1){
                 $page   = 1;
             }
             $start = ($page - 1) * $step;
             $result = EmployeeManager::authCheck($user->id,$storeId,Team::IS_STORE_YES,null,EmployeeManager::TYPE_DEFAULT);
             if ($result['code']!=EmployeeManager::$successCode){
                 throw new Exception($result['message']);
             }
             $matchApply = new MatchApply();
             $count = $matchApply->where('merchant_id',$user->merchant_id)
                 ->where('store_id',$storeId)
                 ->where(function ($query) use($status){
                     if (isset($status)){
                         return $query->where('status',$status);
                     }

                 })
                 ->count();
             $info = $matchApply->where('merchant_id',$user->merchant_id)
                 ->where('store_id',$storeId)
                 ->where(function ($query) use($status){
                     if (isset($status)){
                         return $query->where('status',$status);
                     }

                 })
                 ->order('id desc')->limit($start,$step)->select();
             $pageData = page($count,$step,$page);
             $return['list'] = $info;
             $return = array_merge($return,$pageData);
             self::setStatusCode(self::$successCode);
             self::setMessage(self::$successMessage);
             self::setData($return);
         }catch (Exception $e){
             self::setStatusCode(self::$failCode);
             self::setMessage($e->getMessage());
         }
         return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
     }

    /**
     * 获取门店最后的申请赛事记录
     * @param User $user
     * @param $storeId
     * @return array
     */
     public static function ApplyRecorded(User $user,$storeId)
     {
         try {
             $Record = MatchApply::where('merchant_id',$user->merchant_id)->where('store_id',$storeId)->order('id desc')->find() ?? null;
             self::setStatusCode(self::$successCode);
             self::setMessage(self::$successMessage);
             self::setData($Record);
         }catch (Exception $e){
             self::setStatusCode(self::$failCode);
             self::setMessage($e->getMessage());
         }
         return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
     }


    /**
     * 生成赛事组队小组
     * @param User $user
     * @param $matchId
     * @param $trans
     * @return array
     */
     public static function generate(User $user,$matchId,$nextRound=false,$trans=true)
     {
         if ($trans)
             Db::startTrans();
         try {
             $pr = PublicManager::getPr($user,$matchId,Match::ROUND);
             if ($pr['code'] != self::$successCode){
                 throw new Exception($pr['message']);
             }

             $matchInfo = Match::where('m_id',$matchId)->find();
             if (!$matchInfo){
                 throw new Exception('当前赛事信息不存在');
             }

             $startingRound = null;
             if (!$nextRound){
                 if ($startingRound = Round::where('match_id',$matchId)->where('status',Round::STATUS_STATING)->find()){
                     throw new Exception('当前已有进行中的轮次，请正确操作');
                 }
             }

             if (!$roundInfo = Round::where('match_id',$matchId)->where('status',Round::STATUS_INIT)->order('id asc')->find()){
                 throw new Exception('当前赛事无可进行轮次');
             }

             $innerGroupSwitch = $matchInfo['group_inner_numbers'] ? true : false;
             $result = self::matchGroup($matchId,$roundInfo['id'],$matchInfo['group_people_number'],$innerGroupSwitch,$matchInfo['group_inner_numbers'],false);
             if($result['code'] != self::$successCode){
                 throw new Exception($result['message']);
             }

             if ($nextRound && $startingRound){
                 if(!Match::where('m_id',$matchId)->update(['end_count'=>Db::raw('end_count + 1'),'start_count'=>Db::raw('start_count - 1'),'up_date'=>time()])){
                     throw new Exception('赛事信息更新失败，轮次开始失败');
                 }

                 if(!Round::where('id',$startingRound['id'])->update(['status'=>Round::STATUS_END,'prev_status'=>$startingRound['status'],'update_time'=>time()])){
                     throw new Exception('赛事轮次信息更新失败，轮次开始失败');
                 }
             }

             if(!Match::where('m_id',$matchId)->update(['start_count'=>Db::raw('start_count + 1'),'up_date'=>time()])){
                 throw new Exception('赛事信息更新失败，轮次开始失败');
             }

             if(!Round::where('id',$roundInfo['id'])->update(['status'=>Round::STATUS_STATING,'prev_status'=>$roundInfo['status'],'update_time'=>time()])){
                 throw new Exception('赛事轮次信息更新失败，轮次开始失败');
             }

             if ($trans)
                 Db::commit();
             self::setStatusCode(self::$successCode);
             self::setMessage(self::$successMessage);
         }catch (Exception $exception){
             if ($trans)
                 Db::rollback();
             self::setStatusCode(self::$failCode);
             self::setMessage($exception->getMessage());
         }
         return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
     }

    /**
     * 赛事列表
     * @param $type
     * @param $lat
     * @param $lng
     * @param $radius
     * @param $page
     * @param $step
     * @return array
     */
     public static function matchList($type,$lat,$lng,$radius=5,$page=1,$step=10)
     {
         $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
         try {
             if ($page < 1){
                 $page = 1;
             }

             if ($type==1){
                 $orderBy = 'juli asc';
             }else if($type==2){
                 $orderBy = 'm.release_time desc';
             }else{
                 $orderBy = 'm.people_count desc';
             }

             $distance = null;
             if ($radius){
                 $distance = getDistance($lat,$lng,$radius);
             }
             $where['m.status'] = \app\common\model\Match::STATUS_INIT;
             $where['m.release_time'] = ['<',time()];
             $start = ($page-1)*$step;
             $matchModel = new \app\common\model\Match();
             $count = $matchModel->alias('m')
                 ->where($where)
                 ->where(function ($query) use($distance){
                     if ($distance){
                         if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                             return $query->where('m.lat','between',[$distance['minLat'],$distance['maxLat']])
                                 ->where('m.lng','between',[$distance['minLng'],$distance['maxLng']]);
                         }
                     }
                 })
                 ->where('m.delete',\app\common\model\Match::NO_DELETED)
                 ->count();

             $info = $matchModel->alias('m')
                 ->where($where)
                 ->where(function ($query) use($distance){
                     if ($distance){
                         if (!empty($distance['minLat']) && !empty($distance['maxLat']) && !empty($distance['minLng']) && !empty($distance['maxLng'])){
                             return $query->where('m.lat','between',[$distance['minLat'],$distance['maxLat']])
                                 ->where('m.lng','between',[$distance['minLng'],$distance['maxLng']]);
                         }
                     }
                 })
                 ->where('m.delete',\app\common\model\Match::NO_DELETED)
                 ->field('m.m_id,m.name,m.province,m.city,m.district,m.address,m.lng,m.lat,m.sign_start_date,m.sign_end_date,m.match_date,m.people_count,m.cost,m.join_count,m.order_count,m.avg_amount,m.condition,m.description,m.protocol,m.rounds,m.status,(st_distance(point(m.`lng`,m.lat),point('.$lng.','.$lat.'))*111195/1000 ) as juli')
                 ->order($orderBy)
                 ->limit($start,$step)
                 ->select();

             if($info){
                 foreach ($info as $k=>&$v){
                     $image = RelationImage::where('relation_id',$v['m_id'])->where('type',RelationImage::TYPE_MATCH)->select();

                     if ($image){
                         foreach ($image as $k1=>&$v1){
                             if (strrpos($v1['url'],'https')===false){
                                 $v1['url'] = cdnurl($v1['url']);
                             }
                         }
                     }
                     $memberModel = new \app\common\model\Member();
                     $member = $memberModel->alias('m')
                         ->join('user u','m.user_id=u.id','left')
                         ->where('m.match_id',$v['m_id'])
                         ->where('m.pay_state',\app\common\model\Member::PAY_STATE_SUCCESS)
                         ->field('m.real_name,u.avatar,m.id')
                         ->order('m.id desc')
                         ->limit(0,10)
                         ->select();

                     if ($member){
                         foreach ($member as $mk=>&$mv){
                             if (strrpos($mv['avatar'],'https')===false){
                                 $mv['avatar'] = cdnurl($mv['avatar']);
                             }
                         }
                     }

                     $v['member'] = $member;

                     $v['image'] = $image;

                     if ($v->province){
                         $v->province_text = Region::where('city_code',$v->province)->value('name');
                     }else{
                         $v->province_text = '';
                     }

                     if ($v->city){
                         $v->city_text = Region::where('city_code',$v->city)->value('name');
                     }else{
                         $v->city_text = '';
                     }

                     if ($v->district){
                         $v->district_text = Region::where('city_code',$v->district)->value('name');
                     }else{
                         $v->district_text = '';
                     }

                 }
             }
             $pageData = page($count,$step,$page);
             $return['list'] = $info;
             $return = array_merge($return,$pageData);
             self::setStatusCode(self::$successCode);
             self::setMessage(self::$successMessage);
             self::setData($return);
         }catch (Exception $exception){
             self::setStatusCode(self::$failCode);
             self::setMessage($exception->getMessage());
         }

         return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
     }

    /**
     *
     * @param User|null $user
     * @param $id
     * @param $lng
     * @param $lat
     * @return array
     */
    public static function detail(User $user=null,$id,$lng,$lat)
    {
        try {
            if (!$lng || !$lat){
                throw new Exception('未获取到当前信息');
            }
            $matchModel = new \app\common\model\Match();
            $images = null;

            $info = $matchModel->where('m_id',$id)->fieldRaw('m_id,name,start_count,end_count,province,city,district,address,lng,lat,sign_start_date,sign_end_date,match_date,people_count,cost,join_count,order_count,avg_amount,`condition`,`description`,rounds,`status`,`protocol`,(st_distance(point(`lng`,lat),point('.$lng.','.$lat.'))*111195/1000 ) as juli')->find();
            if ($info){
                if ($info->province){
                    $info->province_text = Region::where('city_code',$info->province)->value('name');
                }else{
                    $info->province_text = '';
                }

                if ($info->city){
                    $info->city_text = Region::where('city_code',$info->city)->value('name');
                }else{
                    $info->city_text = '';
                }

                if ($info->district){
                    $info->district_text = Region::where('city_code',$info->district)->value('name');
                }else{
                    $info->district_text = '';
                }

                $image = RelationImage::where('relation_id',$id)->where('type',RelationImage::TYPE_MATCH)->select();
                if ($image){
                    foreach ($image as &$value){
                        if (strrpos($value['url'],'https')===false){
                            $value['url'] = cdnurl($value['url']);
                        }
                    }
                }
                if (isset($user->id)){
                    $referee = \app\common\model\Referee::where('match_id',$id)->where('user_id',$user->id)->find();
                    if ($referee){
                        $info['referee'] = explode(',',$referee['purview']);
                    }else{
                        $info['referee'] = [];
                    }
                    $info['ordered'] = (Order::where('user_id',$user->id)->where('relation_id',$id)->where('type',Order::TYPE_MATCH)->where('pay_state',Order::PAY_STATE_SUCCESS)->count() > 0 ? Order::PAY_STATE_SUCCESS : 0 );
                    $info['agreement'] = self::isAgreement($user->id,$id);
                    $info['signRecord'] = Signrecord::where('user_id',$user->id)->where('match_id',$id)->count() ? 1 : 0;
                }else{
                    $info['ordered'] = 0;
                    $info['referee'] = [];
                    $info['agreement'] = false;
                    $info['signRecord'] = 0;
                }

                if ($info['start_count'] > 0){
                    $info['round_status'] = 'STARTING';
                }else{
                    if ($info['end_count'] == $info['rounds']){
                        $info['round_status'] = 'END';
                    }else if($info['end_count'] == 0  && $info['start_count'] == 0){
                        $info['round_status'] = 'INIT';
                    }
                }
                $info['image'] = $image;
                $info['current_round'] = bcadd($info['end_count'],$info['start_count']);
            }

            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($info);
        }catch (Exception $e){
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 赛事参与成员
     * @param $id
     * @param $page
     * @param $step
     * @return array
     */
    public static function matchJoiner($id,$page=1,$step=10):array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        try {
            $memberModel = new \app\common\model\Member();
            $count = $memberModel->alias('m')
                ->join('user u','m.user_id=u.id','left')
                ->join('user_account ua','ua.user_id=u.id','left')
                ->where('m.match_id',$id)
                ->where('m.pay_state',\app\common\model\Member::PAY_STATE_SUCCESS)
                ->count();

            $memberInfo = $memberModel->alias('m')
                ->join('user u','m.user_id=u.id','left')
                ->join('user_account ua','ua.user_id=u.id','left')
                ->where('m.match_id',$id)
                ->where('m.pay_state',\app\common\model\Member::PAY_STATE_SUCCESS)
                ->field('m.real_name,m.mobile,u.nickname,u.avatar,ua.join_count,ua.team_count,ua.match_count')->select();
            if ($memberInfo){
                foreach ($memberInfo as $key=>$value){
                    if (empty($value['avatar']) && strrpos($value['avatar'],'https')===false){
                        $memberInfo[$key]['avatar'] = cdnurl($value['avatar']);
                    }
                }
            }
            $return['list'] = $memberInfo;
            $pageData = page($count,$step,$page);
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }


    /**
     * 特殊更新
     * @param $id
     * @param $isTrans
     * @return array
     */
    public static function specialModify($id,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {
            $result = \app\common\model\Match::where(['m_id'=>$id,'join_count'=>Db::Raw('join_count < people_count')])->update(['join_count'=>Db::raw('join_count+1'),'up_date'=>time()]);
            if (!$result){
                throw new Exception('当前赛事已经满员');
            }
            if ($isTrans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $e){
            if ($isTrans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }


    /**
     * 赛事成员插入
     * @param $id
     * @param $data
     * @param $isTrans
     * @return array
     */
    public static function MatchJoinerInsert($id,$data,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {
            $data['match_id'] = $id;
            $info = \app\common\model\Member::create($data);
            if (!$info){
                throw new Exception('赛事参与人员信息插入失败');
            }
            if ($isTrans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($info);
        }catch (Exception $e){
            if ($isTrans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }


    /**
     * 赛事修改
     * @param $id
     * @param $update
     * @param $isTrans
     * @return array
     */
    public static function modify($id,$update,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {
            \app\common\model\Match::update($update,['m_id'=>$id]);
            if ($isTrans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData(['id'=>$id]);
        }catch (Exception $e){
            if ($isTrans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }

        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }

    /**
     * 获取轮次成员信息
     * @param User|null $user
     * @param $matchId
     * @return array
     */
    public static function matchRoundMember(User $user=null,$matchId)
    {
        $data = [];
        try {
            $roundInfo = Round::where('match_id',$matchId)->where('status',Round::STATUS_STATING)->find();
            if (!$roundInfo){
                throw new Exception('当前赛事无进行中轮次');
            }
            $roundMemberModel = new RoundMember();
            $roundMemberInfo = $roundMemberModel->alias('rm')
                ->join('match_member mm','rm.match_id=mm.match_id and mm.id=rm.member_id','inner')
                ->join('user u','u.id=mm.user_id','left')
                ->where('rm.match_id',$matchId)->where('rm.round_id',$roundInfo['id'])
                ->field('rm.id,rm.group_number,rm.group_inner_number,rm.score,mm.real_name,mm.mobile,u.avatar,mm.user_id')
                ->order('rm.group_number asc,rm.group_inner_number asc')
                ->select();
            $data = [];
            $unshift = 0;
            if ($roundMemberInfo){
                foreach ($roundMemberInfo as $key=>&$value){
                    if (!empty($value['avatar']) && strrpos($value['avatar'],'https')===false){
                        $value['avatar'] = cdnurl($value['avatar']);
                    }
                    $data[$value['group_number']]['title'] = '第'.$value['group_number'].'组';
                    $data[$value['group_number']]['inner_group'][$value['group_inner_number']][] = $value;
                    $data[$value['group_number']]['groups'][] = $value;
                    if ($user && $value['user_id'] == $user['id']){
                        $unshift = $value['group_number'];
                    }
                }

                if ($unshift){
                    array_unshift($data,$data[$unshift]);
                    unset($data[$unshift]);
                }
                $data = array_values($data);
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $e){
            self::setStatusCode(self::$failCode);
            self::setMessage($e->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData() ];
    }


    /**
     * 赛事生成小组组队信息
     * @param $matchId
     * @param $roundId
     * @param $groupNum
     * @param $innerGroupSwitch
     * @param $innerGroupNum
     * @param $trans
     * @return array
     */
    public static function matchGroup($matchId,$roundId,$groupNum=4,$innerGroupSwitch=false,$innerGroupNum=2,$trans=true)
    {
        if($trans)
            Db::startTrans();
        try {
            if (!$matchInfo = \app\common\model\Match::where('m_id',$matchId)->where('delete',\app\common\model\Match::NO_DELETED)->find()){
                throw new Exception('当前赛事信息不存在');
            }

            if(!$memberInfo = \app\common\model\Member::where('match_id',$matchId)->where('pay_state',Member::PAY_STATE_SUCCESS)->where('is_out',\app\common\model\Member::NO_OUT)->select()){
                throw new Exception('暂时无可匹配队员');
            }

            $memberCount = count($memberInfo);
            $existsMember = Roundmember::where('match_id',$matchId)->where('round_id',$roundId)->select();
            $existsMemberCount = count($existsMember);
            if($memberCount == $existsMemberCount){
                throw new Exception('当前组队已生成，请勿重复操作');
            }
            $existsMemberArr = $calcMemberArr = [];
            if ($existsMember){
                foreach ($existsMember as  $val){
                    $existsMemberArr[]= $val['member_id'];
                    $calcMemberArr[$val['group_number']]['member_id'][]= $val['member_id'];
                    $calcMemberArr[$val['group_number']]['inner_group'][]= $val['group_inner_number'];
                }
            }
            $groups = ceil($memberCount/$groupNum);
            if ($memberCount &&  $groups < 1){
                throw new Exception('当前成员数量有误');
            }
            $innerGroups = 0;
            if ($innerGroupSwitch && $innerGroupNum){
                if (bcmod($groupNum,$innerGroupNum) != 0){
                    throw new Exception('组人数无法整除组内小组人员数，无法分组');
                }
                $innerGroups = bcdiv($groupNum,$innerGroupNum,0);
            }

            $newMemberArr = [];
            foreach ($memberInfo as $value){
                if (!in_array($value['id'],$existsMemberArr)){
                    $newMemberArr[] = $value['id'];
                }
            }

            $insert = [];
            if ($newMemberArr && $groups && $groupNum){
                for ($k=1;$k<=$groups;$k++){
                    if ($innerGroups && $innerGroupSwitch){
                        for ($v=1;$v<=$innerGroups;$v++){
                            if (isset($calcMemberArr[$k]['inner_group']) && in_array($v,$calcMemberArr[$k]['inner_group'])){
                                $countValues = array_count_values($calcMemberArr[$k]['inner_group']);
                                $executeNum = bcsub($innerGroupNum,$countValues[$v]);
                                if ( $executeNum > 0 && $newMemberArr){
                                    for($ex = 1;$ex<=$executeNum;$ex++){
                                        $newMemberArr = array_values($newMemberArr);
                                        $newMemberArrCount = count($newMemberArr);
                                        $index = mt_rand(0,$newMemberArrCount-1);
                                        $memberId = $newMemberArr[$index];
                                        $insert[] = [
                                            'match_id'=>$matchId,
                                            'round_id'=>$roundId,
                                            'group_number'=>$k,
                                            'group_inner_number'=>$v,
                                            'member_id'=> $memberId,
                                            'create_time'=>time(),
                                            'update_time'=>time(),
                                        ];
                                        unset($newMemberArr[$index]);
                                    }
                                }
                            }else{
                                if ($newMemberArr){
                                    for($ig = 1;$ig<=$innerGroupNum;$ig++){
                                        $newMemberArr = array_values($newMemberArr);
                                        $newMemberArrCount = count($newMemberArr);
                                        $index = mt_rand(0,$newMemberArrCount-1);
                                        $memberId = $newMemberArr[$index];
                                        $insert[] = [
                                            'match_id'=>$matchId,
                                            'round_id'=>$roundId,
                                            'group_number'=>$k,
                                            'group_inner_number'=>$v,
                                            'member_id'=> $memberId,
                                            'create_time'=>time(),
                                            'update_time'=>time(),
                                        ];
                                        unset($newMemberArr[$index]);
                                    }
                                }

                            }
                        }
                    }else{
                        if (array_key_exists($k,$calcMemberArr)){
                            $countValues = count($calcMemberArr[$k]['member_id']);
                            $executeNum = bcsub($groupNum,$countValues);
                            if ( $executeNum > 0 && $newMemberArr){
                                for($ex = 1;$ex<=$executeNum;$ex++){

                                    $newMemberArr = array_values($newMemberArr);
                                    $newMemberArrCount = count($newMemberArr);
                                    $index = mt_rand(0,$newMemberArrCount);
                                    $memberId = $newMemberArr[$index];
                                    $insert[] = [
                                        'match_id'=>$matchId,
                                        'round_id'=>$roundId,
                                        'group_number'=>$k,
                                        'group_inner_number'=>1,
                                        'member_id'=> $memberId,
                                        'create_time'=>time(),
                                        'update_time'=>time(),
                                    ];
                                    unset($newMemberArr[$index]);
                                }
                            }
                        }else{
                            if ($newMemberArr){
                                for($ig = 1;$ig<=$groupNum;$ig++){

                                    $newMemberArr = array_values($newMemberArr);
                                    $newMemberArrCount = count($newMemberArr);
                                    $index = mt_rand(0,$newMemberArrCount-1);
                                    $memberId = $newMemberArr[$index];
                                    $insert[] = [
                                        'match_id'=>$matchId,
                                        'round_id'=>$roundId,
                                        'group_number'=>$k,
                                        'group_inner_number'=>1,
                                        'member_id'=> $memberId,
                                        'create_time'=>time(),
                                        'update_time'=>time(),
                                    ];

                                    unset($newMemberArr[$index]);
                                }
                            }

                        }
                    }

                }
            }
            if ($insert){
                if(!Roundmember::insertAll($insert)){
                    throw new Exception('插入失败');
                }
            }
            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($matchId);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 结束赛事
     * @param User $user
     * @param $matchId
     * @param $trans
     * @return array
     */
    public static function EndMatch(User $user,$matchId,$trans=true)
    {
        if ($trans)
            Db::startTrans();
        try {
            $pr = PublicManager::getPr($user,$matchId,Match::MATCH);
            if ($pr['code'] != self::$successCode){
                throw new Exception($pr['message']);
            }

            if (!$matchInfo = \app\common\model\Match::where('m_id',$matchId)->where('delete',\app\common\model\Match::NO_DELETED)->find()){
                throw new Exception('当前赛事信息不存在');
            }

            if (bcadd($matchInfo['start_count'],$matchInfo['end_count']) < $matchInfo['rounds']){
                throw new Exception('当前赛事有未完成轮次，请正确操作');
            }

            if ($startingRound = Round::where('match_id',$matchId)->where('status',Round::STATUS_STATING)->find()){
                Round::where('id',$startingRound['id'])->update(['status'=>Round::STATUS_END,'prev_status'=>$startingRound['status'],'update_time'=>time()]);
            }

            if(!Match::where('m_id',$matchId)->update(['status'=>Match::STATUS_END,'end_time'=>time(),'up_date'=>time()])){
                throw new Exception('赛事结束失败');
            }

            $redis = new \Redis();
            $config = config('redis');
            $redis->pconnect($config['host'],$config['port']);

            if ($config['password']){
                $redis->auth($config['password']);
            }

            if(!$redis->lpush(Constant::getEndMatchListKey($config['prefix']),$matchId)){
                throw new Exception('赛事结束失败');
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    /**
     * 分数录入
     * @param User $user
     * @param int $matchId
     * @param int $id
     * @param float $score
     * @param bool $trans
     * @return array
     */
    public static function score(User $user,int $matchId,int $id,float $score,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $roundMemberModel = new RoundMember();
            $pr = PublicManager::getPr($user,$matchId,Match::SCORE);
            if ($pr['code'] != self::$successCode){
                throw new Exception($pr['message']);
            }

            if (!$matchInfo = \app\common\model\Match::where('m_id',$matchId)->where('delete',\app\common\model\Match::NO_DELETED)->find()){
                throw new Exception('当前赛事信息不存在');
            }

            if (!$roundMember = $roundMemberModel->lock(true)->where('id',$id)->where('match_id',$matchId)->find()){
                throw new Exception('当前记录不存在');
            }

            $roundInfo = Round::where('id',$roundMember['round_id'])->find();

            if ($roundInfo['status'] != Round::STATUS_STATING){
                throw new Exception('当前轮次已结束，无法录入积分');
            }

            if(!$roundMemberModel->where('id',$id)->update(['score'=>$score,'update_time'=>time()])){
                throw new Exception('积分录入失败');
            }

            $totalScore = bcsub($score,$roundMember['score'],2);
            if(!Member::where('id',$roundMember['member_id'])->setInc('score',$totalScore)){
                throw new Exception('成员积分修改失败，积分录入失败');
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }
    /**
     * 赛事积分排行榜
     * @param $matchId
     * @param $page
     * @param $step
     * @return array
     */
    public static function ranks($matchId,$page,$step=Constant::PAGE_LIMIT):array
    {

        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        if($page < 1){
            $page = 1;
        }
        $start = ($page - 1) * $step;
        try {
            $matchInfo = Match::where('m_id',$matchId)->find();
            if (!$matchInfo){
                throw new Exception('赛事信息不存在');
            }

            $ranks_wait_time = Config::where('name','ranks_wait_time')->value('value');
            if(bcadd($matchInfo['end_time'],$ranks_wait_time) > time()){
                throw new Exception('当前赛事排名正在结算中');
            }

            $memberModel = new Member();
            $count = $memberModel->where('match_id',$matchId)->count();
            $info = $memberModel->alias('mm')
                ->join('user u','u.id=mm.user_id','left')
                ->where('mm.match_id',$matchId)
                ->field('u.avatar,mm.score,mm.real_name,mm.ranks')
                ->order('mm.ranks asc')
                ->limit($start,$step)
                ->select();
            if ($info){
                foreach ($info as &$value){
                    if ($value['avatar'] && strrpos($value['avatar'],'https')===false){
                        $value['avatar'] = cdnurl($value['avatar']);
                    }
                }
            }
            $return['list'] = $info;
            $pageData = page($count,$step,$page);
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    public static function getSignCode($matchId):array
    {
        try {
            $matchInfo = Match::where('m_id',$matchId)->find();
            if (!$matchInfo){
                throw new Exception('当前赛事信息不存在');
            }

            if ($matchInfo['status'] == Match::STATUS_END){
                throw new Exception('当前赛事已结束');
            }

            $roundModel = new Round();
            $roundInfo = $roundModel->where('match_id',$matchId)->where('status',Round::STATUS_STATING)->find();
            if (!$roundInfo){
                throw new Exception('当前赛事无进行中轮次，无法获取签到码');
            }

            $aesService = new Aes(Constant::getAesKey());
            $data['verify_code'] = $aesService->encrypt($matchId);
            self::setData($data);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (\Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    /**
     * 根据轮次码签到
     * @param User $user
     * @param $verifyCode
     * @return void
     */
    /*public static function signRound(User $user,$verifyCode)
    {
        try {
            if (!$verifyCode){
                throw new Exception('请正确访问');
            }
            $aesService = new Aes(Constant::getAesKey());
            $matchId = $aesService->decrypt($verifyCode);
            if (!$matchId){
                throw new Exception('当前二维码信息有误，请联系管理员');
            }

            $matchInfo = Match::where('m_id',$matchId)->find();
            if (!$matchInfo){
                throw new Exception('当前赛事信息不存在');
            }

            if ($matchInfo['status'] == Match::STATUS_END){
                throw new Exception('当前赛事已结束');
            }

            $roundModel = new Round();
            $roundInfo = $roundModel->where('match_id',$matchId)->where('status',Round::STATUS_STATING)->find();
            if (!$roundInfo){
                throw new Exception('当前赛事无进行中轮次，无法签到');
            }

            $memberModel = new Member();
            if (!$memberModel->alias('m')->join('match_round_member mrm','mrm.member_id=m.id','inner')->where('m.match_id',$matchId)->where('mrm.round_id',$roundInfo['id'])->where('m.user_id',$user->id)->count()){
                throw new Exception('您在本轮次无参赛名额，无法签到');
            }

            $signDate = date('Ymd',time());
            if (Signrecord::where('match_id',$matchId)->where('round_id',$roundInfo['id'])->where('user_id',$user->id)->where('sign_date',$signDate)->count()){
                throw new Exception('当前赛事当前轮次今日已签到，请勿重复签到');
            }

            $insertRecord = [
                'user_id'=>$user->id,
                'match_id'=>$matchId,
                'round_id'=>$roundInfo['id'],
                'sign_date'=>$signDate,
                'create_time'=>time(),
            ];
            if(!Signrecord::create($insertRecord)){
                throw new Exception('签到失败');
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (\Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }*/


    /**
     * 根据轮次码签到
     * @param User $user
     * @param $match_id
     * @param $lat
     * @param $lng
     * @return void
     */
    public static function signRound(User $user,$match_id,$lat,$lng):array
    {
        try {
            if (!$lat || !$lng){
                throw new Exception('请正确访问');
            }


            $matchInfo = Match::where('m_id',$match_id)->find();
            if (!$matchInfo){
                throw new Exception('当前赛事信息不存在');
            }

            if ($matchInfo['status'] == Match::STATUS_END){
                throw new Exception('当前赛事已结束');
            }

            if (time() < bcsub($matchInfo['match_date'],30*60)){
                throw new Exception('可签到时间为赛事开始前30分钟');
            }

            $distance = haversine($lat,$lng,$matchInfo['lat'],$matchInfo['lng']);
            $distance = bcadd($distance,0,3);
            if ($distance > 0.3){
                throw new Exception('距离赛事地址过远，无法签到');
            }

//            $roundModel = new Round();
//            $roundInfo = $roundModel->where('match_id',$match_id)->where('status',Round::STATUS_STATING)->find();
//            if (!$roundInfo){
//                throw new Exception('当前赛事无进行中轮次，无法签到');
//            }

            $memberModel = new Member();
            if (!$memberModel->where('match_id',$match_id)->where('user_id',$user->id)->count()){
                throw new Exception('您无参赛名额，无法签到');
            }

            $signDate = date('Ymd',time());
            if (Signrecord::where('match_id',$match_id)->where('user_id',$user->id)->where('sign_date',$signDate)->count()){
                throw new Exception('当前赛事当前轮次今日已签到，请勿重复签到');
            }

            $insertRecord = [
                'user_id'=>$user->id,
                'match_id'=>$match_id,
                'round_id'=>0,
                'sign_date'=>$signDate,
                'create_time'=>time(),
            ];
            if(!Signrecord::create($insertRecord)){
                throw new Exception('签到失败');
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (\Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }
    /**
     * 我参与的赛事
     * @param User $user
     * @param int $page
     * @param int $step
     * @return void
     */
    public static function matchByUser(User $user, int $page=1, int $step=Constant::PAGE_LIMIT):array
    {
        $return = ['total'=>0,'totalPage'=>1,'currentPage'=>$page,'list'=>[]];
        if ($page < 1)
            $page = 1;
        $start = ($page - 1) * $step;
        try {
            $memberModel = new \app\common\model\Member();
            $count = $memberModel->alias('mm')
                ->join('match m','m.m_id=mm.match_id','inner')
                ->where('mm.user_id',$user->id)
                ->count();

            $matchInfo = $memberModel->alias('mm')
                ->join('match m','m.m_id=mm.match_id','inner')
                ->where('mm.user_id',$user->id)
                ->field('m.m_id,m.name,m.address,m.sign_start_date,m.sign_end_date,m.match_date,m.end_time,m.rounds,mm.pay_state')
                ->order('m.m_id desc')
                ->limit($start,$step)
                ->select();
            if ($matchInfo){
                foreach ($matchInfo as $key=>$value){
                    $image = RelationImage::where('type',RelationImage::TYPE_MATCH)->where('relation_id',$value->m_id)->select();
                    if ($image){
                        foreach ($image as $k=>$v){
                            if(strrpos($v['url'],'https')===false){
                                $v['url'] = cdnurl($v['url']);
                            }
                        }
                    }

                    $matchInfo[$key]['image'] = $image;
                }
            }
            $return['list'] = $matchInfo;
            $pageData = page($count,$step,$page);
            $data = array_merge($return,$pageData);
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            self::setData($data);
        }catch (Exception $exception){
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }


    public static function cancelUserMatch(User $user,int $id,$trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {
            $matchInfo = Match::where('m_id',$id)->find();
            if(!$matchInfo){
                throw new Exception('赛事信息不存在');
            }

            if($matchInfo['match_date'] < time()){
                throw new Exception('赛事已开始无法取消');
            }

            if($matchInfo['status'] == Match::STATUS_END){
                throw new Exception('赛事已结束无法取消');
            }

            $payOrderModel = new Order();
            $orderInfo = $payOrderModel->where('user_id',$user->id)->where('type',Order::TYPE_MATCH)->where('relation_id',$id)->where('pay_state',Order::PAY_STATE_SUCCESS)->find();
            if(!$orderInfo){
                throw new Exception('未找到相关支付信息，您无法取消参赛');
            }
            $memberModel = new \app\common\model\Member();
            $info = $memberModel->where('match_id',$id)->where('user_id',$user->id)->find();
            if (!$info){
                throw new Exception('未找到赛事成员中您的信息，无法取消');
            }

            if($info['pay_state'] == Member::PAY_STATE_CANCEL){
                throw new Exception('当前赛事已取消参赛，请勿重复取消');
            }


            if(!Member::where('match_id',$id)->where('user_id',$user->id)->update(['pay_state'=>Member::PAY_STATE_CANCEL,'update_time'=>time()])){
                throw new Exception('取消失败');
            }

            if(
                !Order::where('po_id',$orderInfo['po_id'])
                    ->where('user_id',$orderInfo['user_id'])
                    ->where('type',Order::TYPE_MATCH)
                    ->where('relation_id',$id)
                    ->where('pay_state',Order::PAY_STATE_SUCCESS)
                    ->update([
                        'pay_state'=>Order::PAY_STATE_CANCEL,
                        'cancel_date'=>time(),
                        'up_date'=>time()
                    ])
            ){
                throw new Exception('订单更新失败');
            }

            /*$result = UserAccountManager::money($info['user_id'],$orderInfo['order_money'],UserAccountManager::CHANGE_TYPE_INCOME,time(),UserAccountManager::TYPE_REFUND,['relation_id'=>$info['ut_id']],false);
            if($result['code']!=UserAccountManager::$successCode){
                throw new Exception($result['message']);
            }*/


            $upgradeResult = UserAccountManager::LevelUpgrade($info['user_id'],'downgrade',false);
            if ($upgradeResult['code']!=UserAccountManager::$successCode){
                throw new Exception($upgradeResult['message']);
            }

            if (!UserAccount::where('user_id',$info['user_id'])->where('match_count',Db::raw('match_count >= 1'))->where('join_count',Db::raw('join_count >= 1'))->update(['match_count'=>Db::raw('match_count - 1'),'join_count'=>Db::raw('join_count - 1')])){
                throw new Exception('用户信息更新失败');
            }

            /*$params['title'] = $matchInfo['name'] ?? '其他';
            $params['date'] = date('Y-m-d H:i:s',$matchInfo['match_date']);
            $params['address'] = $matchInfo['address'];
            $params['reason'] = '其他';
            $params['amount'] = $matchInfo['cost'];
            //{"errcode":0,"errmsg":"ok","msgid":3522684900132012041}
            $userInfo = User::where('id',$user->id)->field('mobile,open_id')->find();
            $wechat = new Wechat();
            if (!empty($userInfo['open_id'])){
                $result = $wechat->publishMsg($userInfo['open_id'],$params,Wechat::TEMPLATE_ID_CANCEL,'page_main/views/teamDetails?id='.$id);
                $resultArray = json_decode($result,true);
                if ($resultArray['errcode']!=0){
                    if ($userInfo['mobile']){
                        $alisms = get_addon_config('alisms');
                        $time = date('Y-m-d H:i:s',$matchInfo['match_date']);
                        $teamName = $matchInfo['name'];
                        $name = Authentication::where('user_id',$user->id)->value('real_name') ?? User::where('id',$user->id)->value('nickname');
                        $result  = \app\common\library\Sms::cancel($userInfo['mobile'],['name'=>$name,'time'=>$time,'teamName'=>$teamName],$alisms['template']['cancel']);
                    }

                }
            }else{
                if ($userInfo['mobile']){
                    $alisms = get_addon_config('alisms');
                    $time = date('Y-m-d H:i:s',$matchInfo['match_date']);
                    $teamName = $matchInfo['name'];
                    $name = Authentication::where('user_id',$user->id)->value('real_name') ?? User::where('id',$user->id)->value('nickname');
                    $result  = \app\common\library\Sms::cancel($userInfo['mobile'],['name'=>$name,'time'=>$time,'teamName'=>$teamName],$alisms['template']['cancel']);
                }

            }*/

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    public static function cancelMatchBySystem($id,bool $trans=true):array
    {
        if ($trans)
            Db::startTrans();
        try {

            $matchModel = new Match();
            $matchInfo = $matchModel->where('m_id',$id)->find();
            if (!$matchInfo){
                throw new Exception('赛事信息不存在');
            }
            $matchInfo = $matchInfo->toArray();
            $resultUpdate = $matchModel->where('m_id',$id)->update(['status'=>Match::STATUS_CANCEL,'up_date'=>time()]);
            if(!$resultUpdate){
                throw new Exception('赛事信息更新失败');
            }

            $memberModel = new Member();
            $memberInfo = $memberModel->alias('mm')
                ->join('pay_order po', 'po.po_id=mm.order_id', 'inner')
                ->where('mm.match_id', $id)
                ->where('mm.pay_state', Member::PAY_STATE_SUCCESS)
                ->where('mm.state', Member::STATE_SUCCESS)
                ->field('po.po_id,po.user_id,po.pay_state,po.order_money,po.pay_date,mm.id,mm.match_id,mm.state as mmstate,mm.pay_state as mmpaystate')
                ->select();
            $orderModel = new Order();
            $wechat = new Wechat();

            if ($memberInfo) {
                $mobileArray = [];
                foreach ($memberInfo as $v) {
                    $openId = User::where('id',$v->user_id)->value('open_id');
                    /**
                     * 更新用户支付订单信息，进行退款至余额
                     */
                    if ($v->pay_state == Order::PAY_STATE_SUCCESS) {
                        if (!$orderModel->where('po_id', $v->po_id)->where('pay_state', Order::PAY_STATE_SUCCESS)->update(['pay_state' => Order::PAY_STATE_CANCEL, 'cancel_date' => time(), 'up_date' => time()])) {
                            throw new Exception('成员支付订单更新失败');
                        }

                        $result = UserAccountManager::money($v->user_id, $v->order_money, UserAccountManager::CHANGE_TYPE_INCOME, time(), UserAccountManager::TYPE_MATCH_RETURN, ['relation_id' => $v->id], false);
                        if ($result['code'] != UserAccountManager::$successCode) {
                            throw new Exception($result['message']);
                        }

                        if (!UserAccount::where('user_id', $v->user_id)->where('match_count',Db::raw('match_count >= 1'))->where('join_count',Db::raw('join_count >= 1'))->update(['match_count' => Db::raw('match_count - 1'), 'join_count' => Db::raw('join_count - 1')])) {
                            throw new Exception('用户信息更新失败');
                        }

                        $upgradeResult = UserAccountManager::LevelUpgrade($v->user_id,'downgrade',false);
                        if ($upgradeResult['code']!=UserAccountManager::$successCode){
                            throw new Exception($upgradeResult['message']);
                        }

                        $params['title'] = $matchInfo['name'] ?? '赛事消息';
                        $params['date'] = date('Y-m-d H:i:s',$matchInfo['match_date']);
                        $params['address'] = $matchInfo['address'];
                        $params['reason'] = '参与人员不足取消';
                        $params['amount'] = $matchInfo['cost'];
                        //{"errcode":0,"errmsg":"ok","msgid":3522684900132012041}
                        $mobile = User::where('id',$v->user_id)->value('mobile');
                        if ($openId){
                            $result = $wechat->publishMsg($openId,$params,Wechat::TEMPLATE_ID_CANCEL,config('wechat.team_invite_page').$id);
                            $resultArray = json_decode($result,true);
                            if ($resultArray['errcode']!=0){
                                if ($mobile)
                                    $mobileArray[$v->user_id] = $mobile;
                            }
                        }else{
                            if ($mobile)
                                $mobileArray[$v->user_id] = $mobile;

                        }
                    }
                    /**
                     * 更新用户组队信息状态
                     */
                    if ($v->mmpaystate == Member::PAY_STATE_SUCCESS && $v->mmstate == Member::STATE_SUCCESS) {
                        if (!Member::where('id', $v->id)->where('pay_state', Member::PAY_STATE_SUCCESS)->update(['pay_state' => Member::PAY_STATE_CANCEL, 'is_system' => Member::IS_SYSTEM_YES, 'update_time' => time()])) {
                            throw new Exception('成员参加信息更新失败');
                        }
                    }

                }

                if ($mobileArray){
                    $alisms = get_addon_config('alisms');
                    $time = date('Y-m-d H:i:s',$matchInfo['match_date']);
                    $matchName = $matchInfo['name'];
                    foreach ($mobileArray as $mkey=>$mval){
                        $name = Authentication::where('user_id',$mkey)->value('real_name') ?? User::where('id',$mkey)->value('nickname');
                        $result  = \app\common\library\Sms::cancel($mval,['name'=>$name,'time'=>$time,'teamName'=>$matchName],$alisms['template']['cancel']);
                    }
                }
            }

            if ($trans)
                Db::commit();
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);

        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage().$exception->getLine());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];

    }

    public static function protocolSign($user,$match_id,$url,$trans=true)
    {
        if($trans){
            Db::startTrans();
        }
        try {
            $matchInfo = Match::where('m_id',$match_id)->find();
            if (!$matchInfo){
                throw new Exception('赛事信息不存在');
            }

            if (Agreement::where('match_id',$match_id)->where('user_id',$user->id)->count()){
                throw new Exception('您已签署过协议，请勿重复签署');
            }

            $insertData = [
                'user_id' => $user->id,
                'match_id' => $match_id,
                'url' => $url,
                'create_time' => time()
                ];
            if (!Agreement::create($insertData)) {
                throw new Exception('协议签署失败');
            }
            self::setStatusCode(self::$successCode);
            self::setMessage(self::$successMessage);
            if($trans){
                Db::commit();
            }

        }catch (Exception $exception){
            if($trans){
                Db::rollback();
            }
            self::setStatusCode(self::$failCode);
            self::setMessage($exception->getMessage());
        }
        return ['code'=>self::getStatusCode(),'message'=>self::getMessage(),'data'=>self::getData()];
    }

    public static function isAgreement($user_id,$match_id)
    {
        if (Agreement::where('match_id',$match_id)->where('user_id',$user_id)->count()){
            return true;
        }
        return false;
    }

}